package com.ankifyh.BujoTemplateGenerator;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ResponseUriClickedActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 获取当前地点
        String location = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("location", "火星基地");

        // 读取模板文件内容
        StringBuilder templateStringBuilder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(Constants.LOGSEQ_TEMPLATE_FILE_PATH))) {
            String line;
            while ((line = reader.readLine()) != null) {
                templateStringBuilder.append(line).append("\n"); // 读取每一行，并在行间添加换行符以保持格式
            }
        } catch (IOException e) {
            Toast.makeText(this, "Failed to load template file", Toast.LENGTH_SHORT).show();
            return;
        }
        String templateString = templateStringBuilder.toString();

        // 使用正则表达式匹配第一个由{{{和}}}包裹的内容
        Pattern TimePattern = Pattern.compile("\\{\\{\\{(.+?)\\}\\}\\}");
        Pattern LocalePattern = Pattern.compile("\\[\\[\\[(.+?)\\]\\]\\]");
        Matcher TimeMatcher = TimePattern.matcher(templateString);
        Matcher LocaleMatcher = LocalePattern.matcher(templateString);

        if (TimeMatcher.find() & LocaleMatcher.find()) {
            // 替换{{{xxx}}}为当前日期和时间
            Date currentDate = Calendar.getInstance().getTime();
            // 找到匹配后，group(1) 会包含第一个匹配的内部内容，即 {{{ 和 }}} 之间的部分
            String extractedTimePattern = TimeMatcher.group(1);
            String extractedLocalePattern = LocaleMatcher.group(1);
            String currentTime;
            if (Objects.equals(extractedLocalePattern, "US")) {
                DateFormatSymbols dfs = new DateFormatSymbols(Locale.US);
                SimpleDateFormat sdf = new SimpleDateFormat(extractedTimePattern, dfs);
                currentTime = sdf.format(currentDate);
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat(extractedTimePattern);
                currentTime = sdf.format(currentDate);
            }
            templateString = templateString.replaceAll("\\{\\{\\{.+?\\]\\]\\]", currentTime);

        }


        // 获取剪贴板服务
        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

        // 创建ClipData的Item对象
        ClipData clipData = ClipData.newPlainText("tempString", templateString);

        // 将数据设置到剪贴板
        clipboard.setPrimaryClip(clipData);
        Toast.makeText(this, templateString, Toast.LENGTH_SHORT).show();

        // 检查振动权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.VIBRATE) == PackageManager.PERMISSION_GRANTED) {
            vibrate();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.VIBRATE}, 1);
        }

        // 快速关闭当前Activity
        finish();
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        if (vibrator != null) {
            vibrator.vibrate(200); // 震动500毫秒
        }
    }

    // 重写 onRequestPermissionsResult 方法处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            vibrate();
        } else {
            Toast.makeText(this, "Vibrate permission required.", Toast.LENGTH_SHORT).show();
        }
    }
}
